const Router = require('koa-router');
const router = new Router();
const {db, QueryTypes} = require("../../models/db");

// 恢复票据
router.post('/bill/toRecover', async ctx => {
    try {
        let id = ctx.request.body.ids[0];
        let tenantId = ctx.user.tenantId
        let invoice = await db.models['invoice'].findOne({
            where: {
                tenantId,
                id
            }
        })
        if (!invoice) return ctx.err('没有找到票据')
        if (invoice.billState !== 'del') return ctx.err('只能恢复已删除票据')
        let zq = await db.query(`select * from zq where tenantId=${tenantId} and isCurrent=1 and '${invoice.billDate}' >= zqBeg `, { type: QueryTypes.SELECT, plain: true })
        if (!zq) {
            return ctx.err('不能恢复已结账数据')
        }
        invoice.billState = 'draft'
        invoice.accountedBy = 0
        invoice.isDelete = 0
        invoice.accountedAt = null
        invoice.hxAt = null
        invoice.deletedBy = null
        invoice.deletedAt = null
        await invoice.save()

        return ctx.suc('票据已恢复')
    } catch (e) {
        return ctx.err(e)
    }
})
module.exports = router;